package org.water.datasources.aspect;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.water.datasources.DataSourceName;
import org.water.datasources.DynamicDataSource;
import org.water.datasources.annotation.DataSource;

import java.lang.reflect.Method;

/**
 * 数据源切面处理
 * @author qzy
 *
 */
@Aspect
@Component
public class DataSourceAspect implements Ordered {
	
    protected Logger log = LogManager.getLogger(getClass());

    /**
     * 数据源切点
     */
    @Pointcut("@annotation(org.water.datasources.annotation.DataSource)")
    public void dataSourcePointCut() {

    }

    /**
     * 数据源切点处理
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DataSource ds = method.getAnnotation(DataSource.class);
        if(ds == null){
            DynamicDataSource.setDataSource(DataSourceName.DEFAULT);
            log.debug("切换为默认数据源： " + DataSourceName.DEFAULT);
        }else {
            DynamicDataSource.setDataSource(ds.name());
            log.debug("切换为数据源 " + ds.name());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            log.debug("移除数据源 "+(ds!=null?ds.name():""));
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
